package com.example.demo8.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringUtil implements ApplicationContextAware, BeanFactoryAware {

    private static BeanFactory beanFactory;
    private static ApplicationContext applicationContext;
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        SpringUtil.beanFactory=beanFactory;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtil.applicationContext=applicationContext;
    }

    public static <T> T getBean(Class<T> clazz){
        T bean=null;
        bean = applicationContext.getBean(clazz);
        if (bean==null){
            bean=beanFactory.getBean(clazz);
        }
        return bean;
    }
}
